<?php
class Jssdk{
    private $appId;
    private $appSecret;
    private $cache;
    private $prefix;

    public function __construct($appId,$appSecret,$cache,$prefix) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->cache = $cache;
        $this->prefix = $prefix;
    }

    public function getJsApiTicket() {
        //判断缓存是否存在
        if($this->cache->get($this->prefix.'_ticket')===false){
            //获取access_token
            $accessToken = $this->getAccessToken();
            //获取ticket
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$accessToken;
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            //缓存ticket
            $this->cache->set($this->prefix.'_ticket',$ticket,7200);
        }else{
            //缓存存在直接获取 ticket
            $ticket = $this->cache->get($this->prefix.'_ticket');
        }
        return $ticket;
    }

    //获取access_token
    public function getAccessToken(){
        //判断缓存是否存在
        if($this->cache->get($this->prefix.'_token')===false){
            //获取 access_token
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            //缓存 access_token
            $this->cache->set($this->prefix.'_token',$access_token,7200);
        }else{
            //缓存存在直接获取
            $access_token = $this->cache->get($this->prefix.'_token');
        }
        return $access_token;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}